//
//  Offer_06.swift
//  LeetCode
//
//  Created by migu on 2020/12/8.
//  Copyright © 2020 LBB. All rights reserved.
//  剑指 Offer 06. 从尾到头打印链表
//  输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。

//输入：head = [1,3,2]
//输出：[2,3,1]

import Foundation
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */
public class ListNode {
    public var val:Int
    public var next:ListNode?
    public init(_ val:Int) {
        self.val = val
        self.next = nil
    }
}
class Offer_06 {
    var targetarray:[Int] = []
    func reversePrint(_ head: ListNode?) -> [Int] {
        getValList(head, [])
        var array:[Int] = targetarray;
        for i in 0..<array.count/2 {
            let temp:Int = array[i]
            array[i] = array[array.count - i - 1]
            array[array.count - i - 1] = temp;
        }
        return array
    }
    
    func getValList(_ listNode: ListNode? ,_ valList: [Int]) {
        targetarray = valList
        if listNode?.val != nil {
            targetarray.append(listNode!.val)
        }
        if listNode?.next != nil {
            getValList(listNode?.next, targetarray)
        }
    }
}
